package com.cpsdna.module;

import com.cpsdna.bean.firm.Firm;
import com.cpsdna.bean.user.OperationLog;
import com.cpsdna.bean.user.User;
import com.cpsdna.util.SessionManger;
import com.cpsdna.util.Util;
import eu.bitwalker.useragentutils.UserAgent;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.random.R;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.service.EntityService;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jianghao on 2017/2/27.
 */
@IocBean(fields = {"dao"})
@Ok("json:{locked:'password|salt', ignoreNull:true}")
@Fail("http:500")
@At("/user")
public class UserModule extends EntityService<User> {

    private static final Log log = Logs.get();

    @Ok("raw")
    @At("/checkPasswd")
    public String checkPasswd() {

        String mobile = Mvcs.getReq().getParameter("mobile").trim();
        String password = Mvcs.getReq().getParameter("password");

        if (Strings.isBlank(password))
            return "{\"data\":{\"error\":\"登录密码不能为空\"}}";
        else if (Strings.isBlank(mobile))
            return "{\"data\":{\"error\":\"手机号码不能为空\"}}";
        else if (!Strings.isMobile(mobile))
            return "{\"data\":{\"error\":\"手机号码格式不正确\"}}";
        else {
            User user = dao().fetch(User.class, Cnd.wrap("mobile = '" + Sqls.escapeFieldValue(mobile) + "' " +
                    "and password = md5(concat(md5('" + Sqls.escapeFieldValue(password)
                    + "'), salt))"));
            if (!Lang.isEmpty(user)) {
                if (user.getAccountStatus() == 0)
                    return "{\"data\":{\"error\":\"账号状态异常，请联系管理员\"}}";
                else
                    return "{\"data\":{\"ok\":\"\"}}";
            } else
                return "{\"data\":{\"error\":\"手机号码或登录密码错误\"}}";
        }
    }

    @Ok("raw")
    @At("/verifyMobile")
    public String verifyMobile() {

        String mobile = Mvcs.getReq().getParameter("mobile").trim();

        if (Strings.isBlank(mobile))
            return "{\"data\":{\"error\":\"手机号码不能为空\"}}";
        else if (!Strings.isMobile(mobile))
            return "{\"data\":{\"error\":\"手机号码格式不正确\"}}";
        else {
            User user = dao().fetch(User.class, Cnd.where("mobile", "=", mobile));
            if (!Lang.isEmpty(user))
                return "{\"data\":{\"ok\":\"\"}}";
            else
                return "{\"data\":{\"error\":\"手机号码不存在\"}}";
        }
    }

    @GET
    @At("/index")
    @Ok("beetl:/user/index.btl")
    @Filters(@By(type = CheckSession.class, args = {User.USER_SESSION_KEY, "/login.htm?returnUrl=/user/index.htm"}))
    public Map<String, Object> register() throws IOException {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", SessionManger.getCurrentUser(Mvcs.getReq()));
        return map;
    }

    @Ok("raw")
    @At("/checkpswd")
    public String checkPswd() {

        String password = Mvcs.getReq().getParameter("password");

        if (Strings.isBlank(password))
            return "{\"data\":{\"error\":\"密码不能为空\"}}";
        else {
            User user = SessionManger.getCurrentUser(Mvcs.getReq());

            if (Strings.equals(user.getPassword(), Lang.md5(Lang.md5(password) + user.getSalt())))
                return "{\"data\":{\"ok\":\"成功修改密码后将自动退出系统\"}}";
            else
                return "{\"data\":{\"error\":\"密码错误\"}}";
        }
    }

    @Ok("raw")
    @At("/checkMobile")
    public String checkMobile() {

        String mobile = Mvcs.getReq().getParameter("mobile").trim();

        if (Strings.isBlank(mobile))
            return "{\"data\":{\"error\":\"手机号码不能为空\"}}";
        else if (!Strings.isMobile(mobile))
            return "{\"data\":{\"error\":\"手机号码格式不正确\"}}";
        else {
            User user = dao().fetch(User.class, Cnd.where("mobile", "=", mobile));
            if (Lang.isEmpty(user))
                return "{\"data\":{\"ok\":\"\"}}";
            else
                return "{\"data\":{\"error\":\"手机号码已存在\"}}";
        }
    }

    @POST
    @At("/modify")
    @Ok("redirect:${obj}")
    @Filters(@By(type = CheckSession.class, args = {User.USER_SESSION_KEY, "/login.htm?returnUrl=/user/index.htm"}))
    public String modify(@Param("pswd") String pswd, @Param("nickName") String nickName,
                         @Param("email") String email, @Param("password") String password) {

        try {
            User user = SessionManger.getCurrentUser(Mvcs.getReq());
            if (Strings.isNotBlank(password) && Strings.isNotBlank(pswd)) {
                if (Strings.equals(Lang.md5(Lang.md5(password) + user.getSalt()), user.getPassword())) {
                    user.setSalt(R.UU32());
                    user.setEmail(email);
                    user.setPassword(Lang.md5(Lang.md5(pswd) + user.getSalt()));
                    dao().update(user, "^(password|salt|nickName|email)$");
                    UserAgent userAgent = UserAgent.parseUserAgentString(Mvcs.getReq().getHeader("User-Agent"));
                    OperationLog operationLog = new OperationLog(user.getUserId(), "修改密码", Lang.getIP(Mvcs.getReq())
                            , "操作系统版本（"
                            + userAgent
                            .getOperatingSystem() + "）；浏览器版本（" + userAgent.getBrowser() + "-" + userAgent
                            .getBrowserVersion() + "）", Times.now());
                    dao().insert(operationLog);
                    return "/user/index.htm?alert=success";
                } else
                    return "/user/index.htm?alert=error";
            } else {
                user.setEmail(email);
                user.setNickName(nickName);
                dao().update(user, "^(email|nickName)$");
                UserAgent userAgent = UserAgent.parseUserAgentString(Mvcs.getReq().getHeader("User-Agent"));
                OperationLog operationLog = new OperationLog(user.getUserId(), "修改信息", Lang.getIP(Mvcs.getReq()), "操作系统版本（"
                        + userAgent
                        .getOperatingSystem() + "）；浏览器版本（" + userAgent.getBrowser() + "-" + userAgent
                        .getBrowserVersion() + "）", Times.now());
                dao().insert(operationLog);
                return "/user/index.htm?alert=success";
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "/user/index.htm?alert=error";
        }
    }

    @GET
    @At("/list")
    @Ok("beetl:/user/list.btl")
    @Filters(@By(type = CheckSession.class, args = {User.USER_SESSION_KEY, "/login.htm?returnUrl=/user/list.htm"}))
    public Map<String, Object> list() throws IOException {

        User user = SessionManger.getCurrentUser(Mvcs.getReq());
        if (!Strings.equals(user.getUserGroup(), "{1}"))
            Mvcs.getResp().sendRedirect("/error/403.htm");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        List<User> userList = dao().query(User.class, null);
        dao().fetchLinks(userList, "firm");
        map.put("userList", userList);
        return map;
    }

    @GET
    @At("/add")
    @Ok("beetl:/user/add.btl")
    @Filters(@By(type = CheckSession.class, args = {User.USER_SESSION_KEY, "/login.htm?returnUrl=/user/add.htm"}))
    public Map<String, Object> add() throws IOException {

        User user = SessionManger.getCurrentUser(Mvcs.getReq());
        if (!Strings.equals(user.getUserGroup(), "{1}"))
            Mvcs.getResp().sendRedirect("/error/403.htm");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        map.put("firmList", dao().query(Firm.class, Cnd.where("firm_id", ">", 1)));
        return map;
    }

    @POST
    @At("/add")
    @Ok("redirect:${obj}")
    @Filters(@By(type = CheckSession.class, args = {User.USER_SESSION_KEY, "/login.htm?returnUrl=/user/add.htm"}))
    public String add(@Param("mobile") String mobile, @Param("firmId") String firmId, @Param("nickName") String nickName) {

        User user = SessionManger.getCurrentUser(Mvcs.getReq());
        if (!Strings.equals(user.getUserGroup(), "{1}"))
            return "/error/403.html";

        Firm firm = dao().fetch(Firm.class, Strings.isNotBlank(firmId) ? Integer.parseInt(firmId) : 0);
        if (Strings.isNotBlank(mobile) && Strings.isMobile(mobile) && !Lang.isEmpty(firm)) {

            try {

                User usr = new User();
                usr.setAccountStatus(1);
                usr.setAvatarUrl("");
                usr.setFirmId(firm.getFirmId());
                usr.setMobile(mobile);
                usr.setEmail(Util.phone2Email(mobile));
                usr.setRegistrationIP(Lang.getIP(Mvcs.getReq()));
                usr.setSalt(R.UU32());
                usr.setNickName(nickName);
                usr.setUserGroup("{0}");
                usr.setRegistrationTime(Times.now());
                usr.setPassword(Lang.md5(Lang.md5("dina12345") + usr.getSalt()));
                dao().insert(usr);

                UserAgent userAgent = UserAgent.parseUserAgentString(Mvcs.getReq().getHeader("User-Agent"));
                OperationLog operationLog = new OperationLog(user.getUserId(), "新增用户" + usr.getUserId(), Lang.getIP(Mvcs.getReq
                        ()),
                        "操作系统版本（"
                                + userAgent
                                .getOperatingSystem() + "）；浏览器版本（" + userAgent.getBrowser() + "-" + userAgent
                                .getBrowserVersion() + "）", Times.now());
                dao().insert(operationLog);
                return "/user/add.htm?alert=success";
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return "/user/add.htm?alert=error";
            }
        }
        return "/user/add.htm?alert=error";
    }

    @At("/active")
    @Ok("redirect:${obj}")
    @Filters(@By(type = CheckSession.class, args = {User.USER_SESSION_KEY, "/login.htm?returnUrl=/user/list.htm"}))
    public String active(@Param("userId") String userId, @Param("accountStatus") String accountStatus) {

        User user = SessionManger.getCurrentUser(Mvcs.getReq());
        if (!Strings.equals(user.getUserGroup(), "{1}"))
            return "/error/403.html";
        User usr = dao().fetch(User.class, Cnd.where("user_id", "=", userId));
        if (Lang.isEmpty(userId))
            return "/error/404.html";
        else {
            try {
                if(!Strings.equals(accountStatus, "1") && !Strings.equals(accountStatus, "0"))
                    return "/user/list.htm?alert=error";
                else {
                    UserAgent userAgent = UserAgent.parseUserAgentString(Mvcs.getReq().getHeader("User-Agent"));
                    usr.setAccountStatus(Integer.parseInt(accountStatus));
                    dao().update(usr, "^(accountStatus)$");
                    OperationLog operationLog = new OperationLog(user.getUserId(), "更改用户状态" + usr.getAccountStatus(),
                            Lang.getIP(Mvcs.getReq()),
                            "操作系统版本（"
                                    + userAgent
                                    .getOperatingSystem() + "）；浏览器版本（" + userAgent.getBrowser() + "-" + userAgent
                                    .getBrowserVersion() + "）", Times.now());
                    dao().insert(operationLog);
                    return "/user/list.htm?alert=success";
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return "/user/list.htm?alert=error";
            }
        }
    }
}